package com.pms.partitionPoints.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.SqlHelper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.pms.alarm.entity.KyAlarmRecord;
import com.pms.alarm.mapper.KyAlarmRecordMapper;
import com.pms.partitionPoints.bean.OrgBean;
import com.pms.partitionPoints.entity.*;
import com.pms.partitionPoints.mapper.*;
import com.pms.repair.entity.KyCardRecharge;
import com.pms.repair.entity.KyRechargeHistoricalRecords;
import com.pms.repair.entity.KyRepairDeclare;
import com.pms.repair.entity.KyRepairMaintenance;
import com.pms.repair.mapper.KyCardRechargeMapper;
import com.pms.repair.mapper.KyRechargeHistoricalRecordsMapper;
import com.pms.repair.mapper.KyRepairDeclareMapper;
import com.pms.repair.mapper.KyRepairMaintenanceMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.pms.partitionPoints.service.IKyOrganizationService;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 机构
 *
 * @author lk
 * @email 307169223@qq.com
 * @date 2018-07-18 17:45:06
 */
@Service
public class KyOrganizationServiceImpl extends ServiceImpl<KyOrganizationMapper,KyOrganization> implements IKyOrganizationService {
    /**
     * 根据一级分区id查询 下级  二/三级分区id
     * @param orgId
     * @return
     */
    public List<Integer> getSubordinateOrgIds(Integer orgId){
        return baseMapper.getSubordinateOrgIds(orgId);
    }

    @Override
    public String getGroupIds(String orgIds) {
        return baseMapper.getGroupIds(orgIds);
    }

    @Override
    public String getGroupIdsByEq(String equipmentIds) {
        return baseMapper.getGroupIdsByEq(equipmentIds);
    }

    @Autowired
    KyOrganizationMapper kyOrganizationMapper;
    @Autowired
    KyOrganizationParametersMapper kyOrganizationParametersMapper;
    @Autowired
    KyOrganizationEquipmentMapper kyOrganizationEquipmentMapper;
    @Autowired
    KyEquipmentInfoMapper kyEquipmentInfoMapper;
    @Autowired
    KyAlarmRecordMapper kyAlarmRecordMapper;
    @Autowired
    KyCardRechargeMapper kyCardRechargeMapper;
    @Autowired
    KyRechargeHistoricalRecordsMapper kyRechargeHistoricalRecordsMapper;
    @Autowired
    KyRepairMaintenanceMapper kyRepairMaintenanceMapper;
    @Autowired
    KyRepairDeclareMapper kyRepairDeclareMapper;
    @Autowired
    KyGroupOrganizationMapper kyGroupOrganizationMapper;


    public List<OrgBean> selectByGroupIdAndCode(Long groupId,String code){
        return  kyOrganizationMapper.findByGroupIdAndCode(groupId,code);
    }

    @Override
    public OrgBean sortList(Integer id,List<OrgBean> list,OrgBean orgBean,Set<Integer> parentIdList){
        for(OrgBean bean:list){
            Integer parentId = bean.getParentId();
            Integer nId = bean.getId();
            if(id.intValue()==parentId.intValue()){
//                如果nId不属于父级id集合，则是最底级分区（下面是测点）
                if(!parentIdList.contains(nId)){
                    List<OrgBean> equipments = kyOrganizationMapper.findEquipmentsByOrgId(nId);
                    bean.setChildren(equipments);
                    orgBean.getChildren().add(bean);
                }else {
                    List<OrgBean> equipments = kyOrganizationMapper.getEquipmentsByOrgId(nId);
                    bean = sortList(nId,list,bean,parentIdList);
                    bean.getChildren().addAll(equipments);
                    orgBean.getChildren().add(bean);
                }
//                orgBean.getChildren().add(bean);
            }
        }
        return orgBean;
    }

    public List<String> getOrgIdsByCurrentId(Integer orgId){
        String ids = kyOrganizationMapper.findOrgIdsBycCurrentId(orgId);
        List<String> strList = new ArrayList<String>();
        if(ids!=""&&ids!=null){
            String[] idStr = ids.split(",");
            strList = Arrays.asList(idStr);
        }
        return strList;
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean deleteOrgByIdList(List<String> idList){
        kyOrganizationMapper.deleteOrgByIdList(idList);
        kyOrganizationMapper.deleteOrgEquipmentByIdList(idList);
        kyOrganizationParametersMapper.delete(new EntityWrapper<KyOrganizationParameters>().in("organization_id",idList));
        return  true;
    }

    public List<Map<String,Object>> getEquipmentsByOrgId(Wrapper<KyOrganizationEquipment> wrapper){
        return  kyOrganizationMapper.selectEquipmentsByOrgId(wrapper);
    }

    @Override
    public List<Map<String, Object>> getEquipmentsByOrgIds(String orgIds) {
        return  kyOrganizationMapper.selectEquipmentsByOrgIds(orgIds);
    }

    @Override
    public OrgBean sortOrgList(Integer id,List<OrgBean> list,OrgBean orgBean,Set<Integer> parentIdList){
        for(OrgBean bean:list){
            Integer parentId = bean.getParentId();
            Integer nId = bean.getId();
            if(id.intValue()==parentId.intValue()){
//                如果nId不属于父级id集合，则是最底级分区（下面是测点）
                if(!parentIdList.contains(nId)){
                    orgBean.getChildren().add(bean);
                }else {
                    bean = sortOrgList(nId,list,bean,parentIdList);
                    orgBean.getChildren().add(bean);
                }
            }
        }
        return orgBean;
    }

    public Page<Map<String,Object>> queryOrgPage(Page<Map<String,Object>> page, EntityWrapper ew, String orgIds, String strName){
        SqlHelper.fillWrapper(page,ew);
        page.setRecords(baseMapper.selectOrgPageByOrgIds(page,ew,orgIds,strName));
        return page;
    }

    @Override
    public List<OrgBean> getEquipmentsByOrgId(Integer id){
        return kyOrganizationMapper.getEquipmentsByOrgId(id);

    }
    @Override
    public List<KyOrganization> getOrganizationByRoleTypeAndRoleIdAndCompanyCode(int roleType,long roleId,String code){
        List<KyOrganization> list = new ArrayList<>();
        if(roleType==1){
            list = kyOrganizationMapper.selectList(new EntityWrapper<KyOrganization>().eq("code",code));
        }else{
            list = kyOrganizationMapper.getOrganizationByRoleId(roleId);
        }
        return  list;
    }

    @Override
    public List<Integer> getOrgIdListByCode(String code) {
        return kyOrganizationMapper.getOrgIdListByCode(code);
    }

    @Override
    public List<Integer> getEquipmentIdListByOrgMaxId(Integer orgMaxId) {
        return kyOrganizationMapper.getEquipmentIdListByOrgMaxId(orgMaxId);
    }

    @Transactional
    @Override
    public void deleteSystemByCode(String code) {
        List<Integer> orgIdList = kyOrganizationMapper.getOrgIdListByCode(code);//系统所有分区id
        KyOrganization ko = this.selectOne(new EntityWrapper<KyOrganization>().eq("code",code));//顶级分区
        Integer orgMaxId = ko.getId();//系统顶级分区id
        List<Integer> equipmentIdList = kyOrganizationMapper.getEquipmentIdListByOrgMaxId(orgMaxId);//系统所有测点id
        kyOrganizationParametersMapper.delete(new EntityWrapper<KyOrganizationParameters>().in("organization_id",orgIdList));//删除系统所有分区参数
        kyAlarmRecordMapper.delete(new EntityWrapper<KyAlarmRecord>().in("equipmentId",equipmentIdList));//系统报警信息删除
        kyCardRechargeMapper.delete(new EntityWrapper<KyCardRecharge>().in("equipment_info_id",equipmentIdList));//充值卡删除
        kyRechargeHistoricalRecordsMapper.delete(new EntityWrapper<KyRechargeHistoricalRecords>().in("equipment_info_id",equipmentIdList));//充值记录删除
        kyRepairDeclareMapper.delete(new EntityWrapper<KyRepairDeclare>().in("equipment_info_id",equipmentIdList));//设备保修申报删除
        kyRepairMaintenanceMapper.delete(new EntityWrapper<KyRepairMaintenance>().in("equipment_info_id",equipmentIdList));//设备报修信息删除
        kyGroupOrganizationMapper.delete(new EntityWrapper<KyGroupOrganization>().in("organization_id",orgIdList));//角色分区删除
        kyOrganizationMapper.dropUploadData(orgMaxId);//根据顶级分区id删除对应的数据上报表（删表）
        kyEquipmentInfoMapper.delete(new EntityWrapper<KyEquipmentInfo>().in("id",equipmentIdList));//删除系统所有测点
        kyOrganizationMapper.delete(new EntityWrapper<KyOrganization>().in("id",orgIdList));//删除系统所有分区
        kyOrganizationEquipmentMapper.delete(new EntityWrapper<KyOrganizationEquipment>().in("organizationId",orgIdList));//删除系统所有分区测点关联
    }

    @Override
    public Date getUploadDateByEquipmentId(Integer orgMaxId, Integer equipmentId) {
        return kyOrganizationMapper.selectUploadDateByEquipmentId(orgMaxId,equipmentId);
    }

    @Transactional(rollbackFor=Exception.class)
    @Override
    public void insertOrgMax(KyOrganization ko) {
        kyOrganizationMapper.insert(ko);
        kyOrganizationMapper.createUploadTable(ko.getId());
    }
}